<template>
  <div class="app-container">
    <el-row>
      <el-select v-model="litQuery.status" style="width: 120px" placeholder="状态">
        <el-option v-for="item in [
          {
            label: '全部',
            value: '',
          },
          {
            label: '已审核',
            value: '是否审核',
          },
          {
            label: '已上传',
            value: 'upload',
          },
        ]" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-input v-model="litQuery.s" prefix-icon="el-icon-search" style="margin-left: 5px; width: 250px"
        placeholder="模板、疾病、分组、手术名称" @keyup.enter.native="searcn_but"></el-input>
      <el-button type="warning" @click="searcn_but" round>搜&nbsp;&nbsp;索</el-button>

      <el-dropdown @command="dropdownClick">
        <el-button type="primary">
          更多操作<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="designer">编辑模板</el-dropdown-item>
          <el-dropdown-item command="del">删除模板</el-dropdown-item>
          <!-- <el-dropdown-item command="tplform">表单模板</el-dropdown-item> -->
          <el-dropdown-item command="copy">复制模板</el-dropdown-item>
          <el-dropdown-item command="exportJson">导出模板</el-dropdown-item>
          <el-dropdown-item command="importJson">导入模板</el-dropdown-item>
          <el-dropdown-item command="diftpl">模板对比</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </el-row>
    <el-row>
      <el-table :data="tplData.records" stripe style="width: 100%" @sort-change="sortChange" highlight-selection-row
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <!-- <el-table-column prop="分组编码" label="病组编码"> </el-table-column>
        <el-table-column prop="分组名称" label="病组名称"> </el-table-column>
        <el-table-column prop="疾病编码" label="主诊断编码"></el-table-column>
        <el-table-column prop="疾病名称" label="主诊断名称"></el-table-column> -->
        <!-- <el-table-column prop="手术编码" label="手术编码"></el-table-column>
        <el-table-column prop="手术名称" label="手术名称"></el-table-column> -->

        <el-table-column prop="名称" label="模板名称">
          <!-- <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <div v-for="(it, i) in scope.row.适应疾病" v-bind:key="i">
                {{ it.疾病编码 }}-{{ it.名称 }}
              </div>

              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{
                  scope.row.名称 +
                  (scope.row.适应疾病.length > 0 ? "" : "(未设)")
                }}</el-tag>
              </div>
              
            </el-popover>
          </template> -->
        </el-table-column>
        <el-table-column label="版本" prop="路径版本"> </el-table-column>
        <el-table-column prop="作者" label="创建人"> </el-table-column>
        <el-table-column prop="是否审核" label="是否审核">
          <template slot-scope="scope">
            {{ scope.row.是否审核 ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column prop="模板费用" label="模板费用"> </el-table-column>
        <el-table-column prop="本市标杆" label="医保付费标杆"> </el-table-column>
        <el-table-column prop="本院标杆" label="本院历史标杆"> </el-table-column>
        <el-table-column prop="审核时间" sortable label="审核时间">
        </el-table-column>
        <!-- <el-table-column prop="创建日期" label="创建日期"> </el-table-column> -->
        <el-table-column prop="最近修改日期" sortable label="最近修改日期">
        </el-table-column>
        <el-table-column prop="最近修改人" label="最近修改人">
        </el-table-column>
        <el-table-column label="是否上传" prop="upload" sortable width="100">
          <template slot-scope="scope">
            <i class="el-icon-check" v-if="scope.row.upload"></i>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="上传" width="100">
          <template slot-scope="scope">
            <el-button @click="handlerUpload(scope.row, '路径表单')" type="text" size="small">路径表单</el-button>
            <el-button @click="handlerUpload(scope.row, '路径方案')" type="text" size="small">路径方案</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="litQuery.current" :page-sizes="[5, 10, 20, 50, 100, 200, 300, 400]" :page-size="litQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="litQuery.total">
        </el-pagination>
      </div>
    </el-row>

    <input type="file" @change="fileChnage" id="file" accept="application/json" multiple style="display: none" />

    <el-row>
      <el-dialog :title="uploadTitle" :visible.sync="uploadDialogVisible" width="30%" :before-close="handleClose">
        <el-input v-model="input" style="margin: 5px;" @change="searchFiles" placeholder="请输入内容"></el-input>
        <el-upload class="upload-demo" ref="upload" :action="uploadAction" :headers="upHeaders" :auto-upload="false"
          :limit="100" :file-list="fileList" :multiple="true">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
          <ul class="el-upload-list el-upload-list--text">
            <li v-for="f in fileList2" v-bind:key="f.name" class="el-upload-list__item is-ready">
              <a class="el-upload-list__item-name" target="_blank" @click="gethref(f)">
                <i class="el-icon-document"></i>{{ f.name }}</a>
              <i class="el-icon-close" @click="destoryFile(f)"></i>
            </li>
          </ul>
        </el-upload>
      </el-dialog>
    </el-row>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { delTpls, tplls, copyTpl, GetTplById } from "@/api/pathway";
import { getVersionName } from "@/utils/Utils";
import { saveAs } from "file-saver";
import index from "@/components/Breadcrumb/index.vue";
import { saveTplOther } from "@/api/commonApi";
import { UserModule } from "@/store/modules/user";
import request from "@/utils/request";
import { LsFiles, DestoryFile } from "@/api/commonApi";
import {
  tplDetail,
  saveTpl,
  saveTplDrg,
} from "@/api/PathTemplate";
import { uniqueId } from "xe-utils";
@Component({
  // components: { index },
  name: "pathtemplate",
})
export default class extends Vue {
  private litQuery = {
    page: 1,
    size: 5,
    current: 1,
    total: 0,
    s: "",
    status: "",
    sortprop: "",
    order: "",
  };

  private vn(code: string) {
    return getVersionName(code);
  }

  private sortChange(c: any) {
    this.litQuery.sortprop = c.prop;
    this.litQuery.order = c.order;
    this.search();
  }

  private uploadDialogVisible: boolean = false;
  private uploadTitle: string = "";
  private upHeaders: any = { "X-Access-Token": UserModule.token };

  private downLoadUrl = `${(<any>window).MyConf.APISERVICE}/files/`;

  private uploadAction = `${(<any>window).MyConf.APISERVICE}/api/file-upload`;
  private fileList = [];
  //已上传的列表展示
  private fileList2 = [];

  /**
   * 删除文件
   */
  private destoryFile(f: any) {
    this.$confirm(`删除"${f.name}"该文件将不可恢复，是否要删除？`).then(
      async (va: any) => {
        const { data } = await DestoryFile({ f: f.url });
        let index = this.fileList2.indexOf(f);
        this.fileList2.splice(index, 1);
      }
    );
  }
  submitUpload() {
    let files: any = (<any>this.$refs.upload).uploadFiles.map(
      (it: any) => it.raw
    );
    if (files.length == 0) return;

    let formData = new FormData();
    files.forEach((it: any) => {
      formData.append("files", it, it.name);
    });
    formData.append("tpl", this.tplInfo);
    let loading = this.$loading({ text: "正在上传...." });
    request
      .post(this.uploadAction, formData, {
        headers: { "X-Access-Token": UserModule.token },
      })
      .finally(() => {
        loading.close();
        this.uploadRow.upload = true;
        this.uploadDialogVisible = false;
      });
  }
  private uploadRow: any = {};
  private currentRows: any;
  private tplInfo = "";
  private 模板对比: boolean = false;
  private gethref(f: any) {
    if (this.currentRows.length > 1) {
      this.$alert('请选择一个本院模板进行对比！');
      return;
    }
    if (f.url.startsWith(this.模板对比ID)) {
      this.$router.push({
        path: '/clinicalpathway/templdif',
        query: {
          url: f.url,
          tid: this.currentRows[0].id
        }
      })
      this.handleClose();
      return;
    } else {
      location.href = `${this.downLoadUrl}/${f.url}`;
    }


  }

  private oriFileList: Array<any> = [];
  private async handlerUpload(row: any, t: string) {
    this.fileList = [];
    let d: any = await LsFiles({ tpl: `${row.id}-${t}` });
    let ts = d.data || [];
    this.fileList2 = ts;
    this.oriFileList = ts;
    this.uploadDialogVisible = true;
    this.uploadTitle = `${row.名称}-${t}`;
    this.tplInfo = `${row.id}-${t}`;
    this.uploadRow = row;
    this.模板对比 = !!row.对比;
  }
  private input: string = '';
  private searchFiles(s: string = '') {
    s = s.trim();
    if (s) {
      this.fileList2 = <any>this.oriFileList.filter((it: any) => it.name.indexOf(s) > -1)
    } else this.fileList2 = <any>this.oriFileList;
  }

  private searcn_but() {
    this.litQuery.page = 1;
    this.search();
  }
  private handleClose() {
    this.uploadDialogVisible = false;
  }
  private tplData: any = {};
  private rowClass = (item) => {
    if (!this.currentRows) return "";

    return this.currentRows.some((v) => v.id === item?.row?.id)
      ? "select-row"
      : "";
  };
  //多选
  private handleSelectionChange(ls: Array<any>) {
    this.currentRows = ls;
  }
  private handleSizeChange(val: number) {
    this.litQuery.page = 1;
    this.litQuery.size = val;
    this.search();
  }
  private handleCurrentChange(val: number) {
    this.litQuery.page = this.litQuery.current = val;
    this.search();
  }

  //行双击事件
  private handledbRow_Click() {
    this.dropdownClick("designer");
  }
  private async dropdownClick(command: string) {
    if (command != "importJson") {
      if (!this.currentRows || this.currentRows.length == 0) {
        this.$message.error("请选择要操作的行！（提示：单击数据行）");
      }
    }
    let r = parseInt((Math.random() * 100).toString()).toString();
    //编码模板
    if (command == "designer") {
      this.$router.push({
        path: "/clinicalpathway/tpledit",
        query: {
          tid: this.currentRows[this.currentRows.length - 1].id,
          tn: this.currentRows[this.currentRows.length - 1].名称,
          r: r,
        },
      });
    }

    //删除模板
    if (command == "del") {
      if (UserModule.name !== '管理员') {
        this.$message.error("非管理员帐号禁止删除!");
        return;
      }

      let ids = this.currentRows.map((it: any) => it.id);
      this.$confirm("此操作将永久删除选中的模板, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let r: any = await delTpls({ ids: ids.join(",") });
          if (r.code == 0) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.litQuery.page = 1;
            this.search();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    }
    //复制模板
    if (command == "copy") {
      let edIt: any = this.currentRows[this.currentRows.length - 1];

      this.$router.push({
        path: "/clinicalpathway/copy-tpl",
        query: {
          tid: this.currentRows[this.currentRows.length - 1].id,
        },
      });
    }

    //导出JSON文件
    if (command == "exportJson") {
      if (!this.currentRows || this.currentRows.length == 0) {
        return;
      }
      let name = "";
      if (this.currentRows.length == 1) {
        name = this.currentRows[0].名称;
      } else {
        let date = new Date();
        name = `备份模板_${date.getFullYear()}${date.getMonth()}${date.getDay()}${date.getMilliseconds()}`;
      }
      this.$prompt(`导出名为：`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S{3,}/,
        inputErrorMessage: "至少三个字符",
        inputValue: name,
      })
        .then(async (rr: any) => {
          name = rr.value;
          const loading = this.$loading({
            text: `正在导出${this.currentRows.length}个模板`,
            lock: true,
            background: "rgba(255, 255, 255, 0.1)",
          });
          let ls: Array<any> = [];
          for (let i = 0; i < this.currentRows.length; i++) {
            let tid = this.currentRows[i].id;
            let d = await GetTplById({ id: tid });
            d = d.data;
            let d2 = await tplDetail({ tplid: tid });
            d.data = d2.data;
            ls.push(d);
          }
          this.exportJson(`${name}.json`, ls);
          loading.close();
        })
        .catch(() => { });
    }

    /**
     * 导入
     */
    if (command == "importJson") {
      document.getElementById("file")?.click();
    }

    /**
     * 模板对比
     */
    if (command == "diftpl") {
      let row = { id: this.模板对比ID, 名称: '上传&选择', 对比: true }
      this.handlerUpload(row, '模板对比')
    }
  }
  private 模板对比ID = 'b2aebe8f-f84f-c09e-8959-c5c2a8f248e9';

  private guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

  private fileTimer: any;
  private async fileChnage(ev: any) {
    let files = ev.target.files;
    if (files.length == 0) return;
    const loading = this.$loading({
      text: `正在导入...`,
      lock: true,
      background: "rgba(255, 255, 255, 0.1)",
    });
    for (let i = 0; i < files.length; i++) {
      let fr = new FileReader();
      fr.onloadend = async (e) => {
        let s: any = e.target?.result;
        s = JSON.parse(s);
        if (s) {
          for (let j = 0; j < s.length; j++) {
            // let d = await saveTpl(s[j]);
            try {
              s[j].ls = s[j].data;
              (s[j].ls || []).forEach((it: any) => {
                it.执行性质 = it.选择属性 == '必选' ? 1 : 0
              })
              delete s[j].data;
              let d = await saveTpl({ json: JSON.stringify(s[j]) });
            } catch (error) {

            }
          }
          this.$message.success("导入成功");
        }
        if (!this.fileTimer) {
          clearTimeout(this.fileTimer);
        }
        this.fileTimer = setTimeout(() => {
          loading.close();
          this.search();
        }, 500);
      };
      fr.readAsText(files[i]);

    }
  }
  private exportJson(name: string, data: Array<any>) {
    let blob = new Blob([JSON.stringify(data)], { type: "" });
    saveAs(blob, name);
  }

  private async search() {
    let rs: any = await tplls(this.litQuery);

    rs = rs.data;

    this.tplData = rs;
    this.litQuery.total = this.tplData.total;
  }
  private async created() {
    this.search();
  }
}
</script>

<style lang="scss" scoped>
.el-button {
  margin-left: 5px;
}

.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.block {
  float: right;
  margin-top: 5px;
}

.select-row {
  background-color: #fafafa;
}
</style>
